import Component from '@teld/q-components/Dialog';
import useMappingProps from 't/common/hooks/useMappingProps';
import { useQuasar } from '@teld/q-components';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { computed, defineComponent, onMounted, ref, watch } from 'vue';
import styles from './index.module.scss';
import './index.scss';

export * from '@teld/q-components/Dialog';

export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    show: {
      type: Boolean,
      default() {
        return false;
      },
    },
    autofocus: {
			type: Boolean,
			default: false,
		},
    noShake: {
      type: Boolean,
      default() {
        return true;
      },
    },
    noFocus: {
      type: Boolean,
      default() {
        return true;
      },
    },
    touchHide: {
      type: Boolean,
      default() {
        return true;
      },
    },
    forceTouchHide: {
      type: Boolean,
      default() {
        return false;
      },
    },
    allowFocusOutside:{
      type: Boolean,
      default() {
        return true;
      },
    }

  },
  emits: ['update:show', 'show', 'before-show', 'hide', 'before-hide'],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const isResponsive = ref(false)
    const inDesign = ref(!!window['fas']?.inDesign);
    const $q = useQuasar();
    const showDialog = (IsResponsive)=>{
      mappingProps.show = true;
      isResponsive.value=!!IsResponsive
    }
    const extProps = computed(()=>{
      if(isResponsive.value&&($q.screen.xs || $q.platform.is.mobile)){
        return {
          "full-width":true,
          "full-height":true,
          "maximized":true,
          "position":'right'
        }
      }
      return {}
    })
    const [mappingProps, mappingExpose] = useMappingProps(props, {
      show(evt) {
        refComponent.value.show(evt);
      },
      hide(evt) {
        refComponent.value.hide(evt);
      },
      toggle(evt) {
        refComponent.value.toggle(evt);
      },
      focus(selector) {
        refComponent.value.focus(selector);
      },
      shake(focusTarget) {
        refComponent.value.shake(focusTarget);
      },
      showDialog:showDialog,
      closeDialog() {
        mappingProps.show = false;
      },
      //兼容小写写法
      showdialog:showDialog,
      closedialog() {
        mappingProps.show = false;
      },
    });
    watch(
      () => mappingProps.show,
      (newVal, oldVal) => {
        mappingProps.show = newVal;
      },
    );
    expose(mappingExpose);
    // console.log(mappingProps.show, 'mappingProps.show');
    onMounted(() => {});

    function onClickHandler(params) {}

    let touchHide = {
      offset: 70,
      startX: 0,
      currentX: 0,
      lastTime: Date.now(),
      lastPosition: { x: 0, y: 0 },
      touchstart: e => {
        touchHide.startX = 0;
        touchHide.currentX = 0;
        touchHide.startX = e.touches[0].clientX;

        if (!touchHide.cursor) {
          touchHide.cursor = document.createElement('div');
          touchHide.cursor.className = 'fas-dialog-cursor';
          document.body.appendChild(touchHide.cursor);
        }
        const cursor = touchHide.cursor;
        if (cursor) {
          const touch = e.touches[0];
          cursor.style.left = `${touch.clientX}px`;
          cursor.style.top = `${touch.clientY}px`;
          touchHide.lastPosition = { x: touch.clientX, y: touch.clientY };
          touchHide.lastTime = Date.now();
          touchHide.cursor.style.display = 'none';
        }
      },
      touchmove: e => {
        touchHide.currentX = e.touches[0].clientX;
        let diffX = touchHide.currentX - touchHide.startX;

        const cursor = touchHide.cursor;
        if (false && cursor) {
          /** 在iframe中存在偏移问题 */
          // e.preventDefault(); // 防止页面滚动
          const touch = e.touches[0];
          const x = touch.clientX;
          const y = touch.clientY;
          // 更新光标位置
          cursor.style.left = `${x}px`;
          cursor.style.top = `${y}px`;

          if (x - touchHide.startX > 10) {
            touchHide.cursor.style.display = 'block';
          }

          if (x - touchHide.startX > touchHide.offset) {
            touchHide.cursor.classList.add('effective');
          } else {
            touchHide.cursor.classList.remove('effective');
          }

          const currentTime = Date.now();
          const deltaTime = currentTime - touchHide.lastTime;
          if (deltaTime > 30) {
            // 控制拖影生成频率
            const deltaX = x - touchHide.lastPosition.x;
            const deltaY = y - touchHide.lastPosition.y;
            const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);

            // 生成拖影
            if (distance > 5) {
              // 避免过于密集的拖影
              const trail = document.createElement('div');
              trail.className =
                'fas-dialog-trail' +
                (x - touchHide.startX > touchHide.offset ? ' effective' : '');
              trail.style.left = `${x}px`;
              trail.style.top = `${y}px`;
              document.body.appendChild(trail);

              // 移除拖影
              setTimeout(() => {
                trail.remove();
              }, 500); // 与 CSS 动画时间一致
            }

            touchHide.lastPosition = { x, y };
            touchHide.lastTime = currentTime;
          }
        }
      },
      touchend: () => {
        if (touchHide.currentX - touchHide.startX > touchHide.offset) {
          refComponent.value.hide();
        }
        if (touchHide.cursor) {
          touchHide.cursor.style.display = 'none';
          // touchHide.cursor.remove();
          // touchHide.cursor = null;
        }
      },

      iframeTouchHandler(e) {
        const { type, data } = e.data;
        touchHide[type]?.(data);
      },
      setupIframeTouchEvent(el) {
        const interIframe = el.querySelectorAll('iframe');
        touchHide.iframes = interIframe;
        touchHide.iframes.forEach(iframe => {
          iframe.addEventListener('load', loadArgs => {
            const {
              contentWindow: iframeWindow,
              contentDocument: iframeDocument,
            } = loadArgs.target;
            const iframeBody = iframeDocument?.body;

            if (iframeBody) {
              const iframeTouchEvent = (iframeBody.iframeTouchEvent =
                function iframeTouchEvent(touchArgs) {
                  const props = [
                    'clientX',
                    'clientY',
                    'force',
                    'identifier',
                    'pageX',
                    'pageY',
                    'radiusX',
                    'radiusY',
                    'rotationAngle',
                    'screenX',
                    'screenY',
                  ];

                  const touches = [...touchArgs.touches].map(touch => {
                    const touchData = {};
                    props.forEach(prop => {
                      touchData[prop] = touch[prop];
                    });
                    return touchData;
                  });

                  iframeWindow.parent.postMessage(
                    {
                      type: touchArgs.type,
                      data: { touches: touches },
                    },
                    '*',
                  );
                });

              iframeBody.addEventListener('touchstart', iframeTouchEvent);
              iframeBody.addEventListener('touchmove', iframeTouchEvent);
              iframeBody.addEventListener('touchend', iframeTouchEvent);
            }
          });
          iframe.addEventListener('unload', unloadArgs => {
            const {
              contentWindow: iframeWindow,
              contentDocument: iframeDocument,
            } = unloadArgs.target;
            const iframeBody = iframeDocument?.body;

            if (iframeBody) {
              const iframeTouchEvent = iframeBody.iframeTouchEvent;
              iframeBody.removeEventListener('touchstart', iframeTouchEvent);
              iframeBody.removeEventListener('touchmove', iframeTouchEvent);
              iframeBody.removeEventListener('touchend', iframeTouchEvent);
            }
          });
        });
        window.addEventListener('message', touchHide.iframeTouchHandler);
      },

      setup() {
        let p = {
          maximized: mappingProps?.maximized,
          position: mappingProps?.position,
          ...extProps.value,
        };
        if (
          (p.maximized && 'right' == p.position) ||
          mappingProps.forceTouchHide
        ) {
          const el = refComponent.value.contentEl || document.body;
          touchHide.target = el;
          touchHide.target.addEventListener('touchstart', this.touchstart);
          touchHide.target.addEventListener('touchmove', this.touchmove);
          touchHide.target.addEventListener('touchend', this.touchend);
          touchHide.setupIframeTouchEvent(el);
        }
      },
      destroy() {
        document.body.removeEventListener('touchstart', this.touchstart);
        document.body.removeEventListener('touchmove', this.touchmove);
        document.body.removeEventListener('touchend', this.touchend);
        window.removeEventListener('message', touchHide.iframeTouchHandler);
        if (touchHide.cursor) {
          touchHide.cursor.remove();
          touchHide.cursor = null;
        }
      },
    };

    function onHide(params) {
      emit('update:show', false);
      emit('hide', params);
    }
    function onShow(params) {
      emit('show', params);
      mappingProps.touchHide && touchHide.setup();
    }
    function onBeforeShow(params) {
      emit('before-show', params);
    }
    function onBeforeHide(params) {
      emit('before-hide', params);
      touchHide.destroy();
    }
    return () => {
      return (
        <Component
          ref={refComponent}
          {...attrs}
          {...pickOwnForBasicComponent(mappingProps, Component.props, attrs)}
          persistent={inDesign.value ? true : mappingProps.persistent}
          class={['tr-dialog', styles.module]}
          onClick={onClickHandler}
          onHide={onHide}
          onShow={onShow}
          onBeforeShow={onBeforeShow}
          onBeforeHide={onBeforeHide}
          v-model={mappingProps.show}
          {...extProps.value}
          class={Object.keys(extProps.value).length?'isMobile':''}
          // v-slots={{ ...slots }}
        >
          {slots}
        </Component>
      );
    };
  },
});
